package com.xzsoft.gdwz.schedual;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.suning.api.DefaultSuningClient;
import com.suning.api.entity.govbus.ConfirmOrderAddRequest;
import com.suning.api.entity.govbus.ConfirmOrderAddResponse;
import com.suning.api.entity.govbus.RejectOrderDeleteRequest;
import com.suning.api.entity.govbus.RejectOrderDeleteResponse;
import com.suning.api.exception.SuningApiException;
import com.xzsoft.gdwz.common.HttpClientUtil;
import com.xzsoft.gdwz.model.TrdPsEmInfLog;
import com.xzsoft.gdwz.model.UserToken;
import com.xzsoft.gdwz.services.ConfirmOrCancleOrder;
import com.xzsoft.gdwz.services.RefreshTokenServices;
import com.xzsoft.gdwz.services.TrdPsEmInfLogService;
/**
 * 
 * <p>Title: </p>
 * <p>Description: 电商确认订单、取消订单</p>
 * <p>Company:兴竹信息 </p>
 * @author:杨   光
 * @date:2016-9-7 下午2:24:18
 */
@Component
public class ConfirmOrCancleOrderImpl implements ConfirmOrCancleOrder {

	Logger logger = Logger.getLogger(ConfirmOrCancleOrderImpl.class); 
	
	@Autowired
	private RefreshTokenServices refreshTokenServices;
	
	@Autowired
	private TrdPsEmInfLogService trdPsEmInfLogService;
	
	@Override
	public boolean JDConfirmOrder(String jdOrderId) {
		UserToken token = refreshTokenServices.getToken("JD");
		String url = token.getConfirmOrderUrl();
		Map<String,String> map = new HashMap<String,String>();
		String accessToken = token.getAccessToken();
		map.put("token", accessToken);  
		map.put("jdOrderId", jdOrderId);
		String result = HttpClientUtil.httpPost(url, map);
		logger.info("京东确认订单结果"+result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		if("token已过期".equals(jsonObject.get("resultMessage"))){
			refreshTokenServices.refreshToken("JD");
			JDConfirmOrder(jdOrderId);
		}
		boolean success = (Boolean)jsonObject.get("result");
		if(!success){
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName("JD");
			log.setErrorMsg(jsonObject.get("resultMessage").toString());
			log.setHasRecieve("0");
			log.setOrderId(jdOrderId);
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
			logger.info("错误信息:"+jsonObject.get("resultMessage").toString());
		}
		return success;
	}

	@Override
	public boolean JDCancleOrder(String jdOrderId) {
		UserToken token = refreshTokenServices.getToken("JD");
		String url = token.getCancelOrderUrl();
		Map<String,String> map = new HashMap<String,String>();
		String accessToken = token.getAccessToken();
		map.put("token", accessToken);
		map.put("jdOrderId", jdOrderId);
		String result = HttpClientUtil.httpPost(url, map);
		JSONObject jsonObject = JSONObject.fromObject(result);
		logger.info("京东取消订单结果："+result);
		logger.info("京东jsonObject"+jsonObject);
		if("token已过期".equals(jsonObject.get("resultMessage"))){
			refreshTokenServices.refreshToken("JD");
			JDCancleOrder(jdOrderId);
		}
		boolean success = (Boolean)jsonObject.get("result");
		if(!success){
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName("JD");
			log.setErrorMsg(jsonObject.get("resultMessage").toString());
			log.setHasRecieve("0");
			log.setOrderId(jdOrderId);
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
			logger.info("错误信息:"+jsonObject.get("resultMessage").toString());
		}
		return success;
	}
    
	@Override
	public boolean SNConfirmOrder(String snorderId) {
		UserToken userToken = refreshTokenServices.getToken("SN");
		String serverUrl = userToken.getConfirmOrderUrl();
		String appKey = userToken.getUsername();
		String appSecret = userToken.getPassword();
		ConfirmOrderAddRequest request = new ConfirmOrderAddRequest();
		request.setOrderId(snorderId);
		request.setCheckParam(true);
		DefaultSuningClient client = new DefaultSuningClient(serverUrl, appKey,
				appSecret, "json");
		String unCampSuccess = null;
		try {
			ConfirmOrderAddResponse response = client.excute(request);
			logger.info("返回json/xml格式数据 :" + response.getBody());
			JSONObject Body = JSONObject.fromObject(response.getBody());
			JSONObject sn_responseContent = (JSONObject)Body.get("sn_responseContent");
			JSONObject sn_body = (JSONObject)sn_responseContent.get("sn_body");
			if(sn_body==null){
				JSONObject sn_error = (JSONObject) sn_responseContent.get("sn_error");
				String error_msg = (String) sn_error.get("error_msg");
				TrdPsEmInfLog log = new TrdPsEmInfLog();
				log.setId(UUID.randomUUID().toString());
				log.setEmName("SN");
				log.setErrorMsg(error_msg);
				log.setHasRecieve("0");
				log.setOrderId(snorderId);
				trdPsEmInfLogService.insertTrdPsEmInfLog(log);
				logger.info("错误信息:"+error_msg);
				return false;
			}else{
				JSONObject addConfirmOrder = (JSONObject)sn_body.get("addConfirmOrder");
				unCampSuccess = (String)addConfirmOrder.get("campSuccess");
				System.out.println(unCampSuccess);
			}
		} catch (SuningApiException e) {
			e.printStackTrace();
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName("SN");
			log.setErrorMsg(e.getMessage());
			log.setHasRecieve("0");
			log.setOrderId(snorderId+"");
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
		}
		if(unCampSuccess.equals("Y")){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean SNCancleOrder(String snorderId) {
		UserToken userToken = refreshTokenServices.getToken("SN");
		String serverUrl = userToken.getCancelOrderUrl();
		String appKey = userToken.getUsername();
		String appSecret = userToken.getPassword();
		RejectOrderDeleteRequest request = new RejectOrderDeleteRequest();
		request.setOrderId(snorderId);
		request.setCheckParam(true);
		DefaultSuningClient client = new DefaultSuningClient(serverUrl, appKey,
				appSecret, "json");
		String unCampSuccess = null ;
		try {
			RejectOrderDeleteResponse response = client.excute(request);
			logger.info("返回json/xml格式数据 :" + response.getBody());
			JSONObject Body = JSONObject.fromObject(response.getBody());
			JSONObject sn_responseContent = (JSONObject)Body.get("sn_responseContent");
			JSONObject sn_body = (JSONObject) sn_responseContent.get("sn_body");
			if(sn_body==null){
				JSONObject sn_error = (JSONObject) sn_responseContent.get("sn_error");
				String error_msg = (String) sn_error.get("error_msg");
				TrdPsEmInfLog log = new TrdPsEmInfLog();
				log.setId(UUID.randomUUID().toString());
				log.setEmName("SN");
				log.setErrorMsg(error_msg);
				log.setHasRecieve("0");
				log.setOrderId(snorderId);
				trdPsEmInfLogService.insertTrdPsEmInfLog(log);
				logger.info("错误信息:"+error_msg);
				return false;
			}else{
				JSONObject deleteRejectOrder = (JSONObject) sn_body.get("deleteRejectOrder");
				unCampSuccess = (String)deleteRejectOrder.get("unCampSuccess");
				logger.info(unCampSuccess);
			}
		} catch (SuningApiException e) {
			e.printStackTrace();
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName("SN");
			log.setErrorMsg(e.getMessage());
			log.setHasRecieve("0");
			log.setOrderId(snorderId+"");
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
		}
    	if(unCampSuccess.equals("N")){
    		return true;
    	}else{
    		return false;
    	}
	}

	@Override
	public boolean DLConfirmOrder(String dlorderId) {
		//refreshTokenServices.refreshToken("DL");
		UserToken token = refreshTokenServices.getToken("DL");
		String url = token.getConfirmOrderUrl();
		Map<String,String> map = new HashMap<String,String>();
		String accessToken = token.getAccessToken();
		map.put("Token", accessToken);  
		map.put("OrderId", dlorderId);
		String result = HttpClientUtil.httpPost(url, JSONObject
				.fromObject(map).toString());
		//String result = HttpClientUtil.httpPost(url, map);
		JSONObject jsonObject = JSONObject.fromObject(result);
		logger.info(jsonObject);
		if("密钥验证失败".equals(jsonObject.get("ResultMessage"))){
			refreshTokenServices.refreshToken("DL");
			DLConfirmOrder(dlorderId);
		}
		boolean success = (Boolean)jsonObject.get("Success");
		if(!success){
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName("DL");
			log.setErrorMsg((String) jsonObject.get("ResultMessage"));
			log.setHasRecieve("0");
			log.setOrderId(dlorderId);
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
		}
		return success;			
	}

	@Override
	public boolean DLCancleOrder(String dlorderId) {
		UserToken token = refreshTokenServices.getToken("DL");
		//refreshTokenServices.refreshToken("DL");
		String url = token.getCancelOrderUrl();
		Map<String,String> map = new HashMap<String,String>();
		String accessToken = token.getAccessToken();
		map.put("Token", accessToken);
		map.put("OrderId", dlorderId);
		String result = HttpClientUtil.httpPost(url, JSONObject
				.fromObject(map).toString());
		JSONObject jsonObject = JSONObject.fromObject(result);
		logger.info(jsonObject);
		boolean success = (Boolean)jsonObject.get("Success");
		if("密钥验证失败".equals(jsonObject.get("ResultMessage"))){
			refreshTokenServices.refreshToken("DL");
			DLCancleOrder(dlorderId);
		}
		if(!success){
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName("DL");
			log.setErrorMsg((String) jsonObject.get("ResultMessage"));
			log.setHasRecieve("0");
			log.setOrderId(dlorderId);
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
		}
		return success;
	}
    
	@Override
	public boolean XYConfirmOrConcleOrder(String xyorderId,String status ) {
		//refreshTokenServices.setXyToken();
		UserToken token = refreshTokenServices.getToken("XY");
		String url = token.getConfirmOrderUrl();
		String accessToken = token.getAccessToken();
		Map<String,String> map = new HashMap<String, String>();
		map.put("token", accessToken);
		map.put("order_id", xyorderId);
		map.put("status", status);
		logger.info("西域确认取消订单参数"+map);
		String result = HttpClientUtil.httpPost(url,map);
		logger.info(result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		logger.info(jsonObject);
		String success =   jsonObject.get("status").toString();
		logger.info(success);
		String Message = (String) jsonObject.get("message");
		Object Data =  jsonObject.get("data");
		boolean returndate = false ;
		//获取Token失败需要刷新Token  setXyToken
		if("登录状态已过期,请重新登录".equals(jsonObject.get("message"))||
				"你的账号已经在其他设备登录,请重新登录或修改密码".equals(jsonObject.get("message"))){
			refreshTokenServices.setXyToken();
			XYConfirmOrConcleOrder(xyorderId,status);
			}
		if(success==null||"".equals(success)||!success.equals("0")){
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName("XY");
			log.setErrorMsg(Message);
			log.setHasRecieve("0");
			log.setOrderId(xyorderId);
			log.setOrderInfo(Data.toString());
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
			returndate = false;
		}else if(success.equals("0")){
			returndate = true;
		}
		return returndate;
	}

}
